import {
  getSendCode,
  postRegister,
  postLogin,
  getUserInfo,
  getLogout,
  getFindUserAddressList,
} from '@/api/user'
import { Message } from 'element-ui'
import router from '@/router'
export default {
  namespaced: true,
  state: {
    token: null,
    userInfo: {},
    addressList: [],
  },
  mutations: {
    //id设为默认的id
    UP_ADDRESS_BY_ID(state, id) {
      state.addressList = state.addressList.map((item) => {
        if (item.isDefault === '1') item.isDefault = '0'
        if (item.id === id) item.isDefault = '1'
        return item
      })
    },
    //更新用户地址列表信息
    UP_ADDRESSLIST(state, payload) {
      state.addressList = payload
    },
    //更新init
    UP_INIT(state) {
      ;(state.token = null), (state.userInfo = {})
    },
    //更新token
    UP_TOKEN(state, payload) {
      state.token = payload
    },
    //更新个人信息
    UP_USERINFO(state, payload) {
      state.userInfo = payload
    },
  },
  actions: {
    async getSendCodeAsync(context, phone) {
      const res = await getSendCode(phone)
      return res.data
    },
    async postRegisterAsync(context, body) {
      const res = await postRegister(body)
      return res
    },
    //获取个人信息
    async getUserInfoAsync({ commit }) {
      const res = await getUserInfo()
      commit('UP_USERINFO', res.data)
      return res
    },
    //获取登录信息
    async postLoginAsync({ dispatch, commit }, body) {
      if (body.phone.length === 0) {
        Message.error('请输入手机号')
        return
      }
      if (body.password.length === 0) {
        Message.error('请输入密码')
        return
      }
      const { ok, message, data } = await postLogin(body)
      if (ok) {
        commit('UP_TOKEN', data.token)
        await dispatch('getUserInfoAsync')
        Message.success('恭喜，登录成功!')
        router.push('/')
      } else {
        Message.error('账号或密码不正确')
      }
    },
    //退出登录
    async getLogoutAsync({ commit }) {
      await getLogout()
      commit('UP_INIT')
      Message.success('退出成功')
      router.push('/login')
    },
    //获取用户地址列表信息
    async getFindUserAddressListAsync({ commit }) {
      const res = await getFindUserAddressList()
      commit('UP_ADDRESSLIST', res.data)
    },
  },
  getters: {
    getDefaultAddress(state) {
      return state.addressList.find((v) => v.isDefault === '1')
    },
  },
}
